let baseURL = "https://chuangmou.axu9.com/api/"
let uploadAudioUrl = "v1.home/file"; //上传音频
// let uploadImgUrl = "v1.home/file"; //上传图片
let uploadAudioNewUrl = "v1.home/file_audio"; //上传音频--音色
let uploadvideoNewUrl = "v1.home/file"; //上传视频
let uploadvideoQiniuUrl = "https://up-z2.qiniup.com"; //上传视频到七牛云
let getQiniuTokenUrl = 'v1.home/qiniu_token'; //七牛云获取token
let qiniuDomainUrl = 'https://audiovideo.axa2.com/';
let token = ""; // 一般用户的token 
let volunteerToken = ""; // 志愿者固有的token 
export const completQiniuUploadUrl = 'https://up-z2.qiniup.com';
// export const qiniuDomainUrlD = 'https://audiovideo.axa2.com/';
export const qiniuDomainUrlD = 'https://chuangmouqiniu.axu9.com/';
export const baseImgURL = 'https://chuangmou.axu9.com/images';
export const myRequest = (options) => {
	return new Promise((resolve, reject) => {
		// console.log(baseURL + options.url,'请求++++++++++++++++++++');
		uni.request({
			url: baseURL + options.url, //接口地址：前缀+方法中传入的地址    
			method: options.method || "GET", //请求方法：传入的方法或者默认是“GET”    
			data: options.data || {}, //传递参数：传入的参数或者默认传递空集合    
			header: {
				// "api-token": uni.getStorageSync("token"), //自定义请求头信息      
			},
			success: (
				res
			) => { //返回的数据（不固定，看后端接口，这里是做了一个判断，如果不为true，用uni.showToast方法提示获取数据失败)     // 如果不满足上述判断就输出数据     
				// console.log(res.data.code,'uni.request',options.url)

				if (res.data.errno == 1 || res.data.errno == 0) {
					resolve(res.data)
				} else if (res.data.errno == 401) {


					uni.redirectTo({
						url: '/pages/login/login'
					})

				} else {

					reject();
				}
			}, // 这里的接口请求，如果出现问题就输出接口请求失败    
			fail: (err) => {
				// console.log(err)    
				reject(err)
			},
		})
	})

}


//图片上传
export function uploadImg(types) {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册选择
			type: 'image',
			extension: ['.png', 'jpg'],
			success: (res) => {
				console.log(res, '上传图片')
				const tempFilePaths = res.tempFilePaths[0];
				const uploadTask = uni.uploadFile({
					url: baseURL + uploadImgUrl, //图片上传地址
					formData: {
						// 'folderType': types
					},
					filePath: tempFilePaths,
					name: 'file',
					success: (uploadFileRes) => {

						let logo = JSON.parse(uploadFileRes.data);
						console.log(logo, 'logo')
						resolve(logo)
					}
				});
			},
			error: (e) => {
				reject(e)
			}
		});
	});
}

//图片上传
export function upload(tempurl) {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '上传中'
		})
		const uploadTask = uni.uploadFile({
			url: baseURL + uploadAudioNewUrl, //音频上传地址
			formData: {
				// 'folderType': types
			},
			filePath: tempurl,
			name: 'file',
			success: (uploadFileRes) => {
				uni.hideLoading()
				let logo = JSON.parse(uploadFileRes.data);
				console.log(logo, 'logo')
				resolve(logo)
			},
			fail: (err) => {
				uni.hideLoading()
				reject(err)
			}
		});
	});
}
export function uploadAvatar(tempurl) {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '上传中'
		})
		const uploadTask = uni.uploadFile({
			url: baseURL + uploadAudioUrl, //音频上传地址
			formData: {
				// 'folderType': types
			},
			filePath: tempurl,
			name: 'file',
			success: (uploadFileRes) => {
				uni.hideLoading()
				let logo = JSON.parse(uploadFileRes.data);
				console.log(logo, 'logo')
				resolve(logo)
			},
			fail: (err) => {
				uni.hideLoading()
				reject(err)
			}
		});
	});
}

//音频上传
export function uploadAudio(types) {
	return new Promise((resolve, reject) => {
		// console.log(types,'types')
		const tempFilePaths = types;
		// console.log(tempFilePaths,'tempFilePaths')
		const uploadTask = uni.uploadFile({
			url: baseURL + uploadAudioNewUrl,
			formData: {
				// 'folderType': types
			},
			filePath: tempFilePaths,
			name: 'file',
			success: (uploadFileRes) => {
				// console.log(JSON.parse(uploadFileRes.data),'JSON.parse(uploadFileRes.data)')
				let logo = JSON.parse(uploadFileRes.data).data;
				let name = types.split("/").slice(-1)
				// console.log(logo,name,'logo')
				let data = {
					res: logo,
					name: name[0]
				}
				resolve(data)
			}
		});
	});
}
// 视频上传
export function uploadVideo(tempurl) {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '上传中'
		})
		const uploadTask = uni.uploadFile({
			url: baseURL + uploadvideoNewUrl, //视频上传地址
			formData: {
				// 'folderType': types
			},
			filePath: tempurl,
			name: 'file',
			success: (uploadFileRes) => {
				uni.hideLoading()
				let logo = JSON.parse(uploadFileRes.data);
				console.log(logo, 'logo')
				resolve(logo)
			},
			fail: (err) => {
				uni.hideLoading()
				uni.showToast({
					title: '上传失败',
					icon: 'none'
				})
				reject(err)
			}
		});
	});
}

function generateRandomString(length) {
	const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	let result = '';
	const charactersLength = characters.length;
	for (let i = 0; i < length; i++) {
		result += characters.charAt(Math.floor(Math.random() * charactersLength));
	}
	return result;
}

// 视频上传到七牛云
export function uploadVideoQiniu(tempurl) {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '上传中'
		})
		var timestamp = Date.now();
		var userId = uni.getStorageSync('userId');
		var name = userId + '/' + generateRandomString(8) + timestamp;
		uni.request({
			url: baseURL + getQiniuTokenUrl,
			success(res) {
				console.log(res, '获取token')
				let token = res.data.data;
				const uploadTask = uni.uploadFile({
					filePath: tempurl,
					name: 'file',
					url: uploadvideoQiniuUrl,
					timeout: 1000000,
					formData: {
						token: token,
						key: name
					},
					success: (uploadFileRes) => {
						uni.hideLoading()
						let logo = JSON.parse(uploadFileRes.data);
						console.log(logo, 'logo')
						resolve(qiniuDomainUrl + logo.key)
					},
					fail: (err) => {
						uni.hideLoading()
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						})
						reject(err)
					}
				})
				// // 监听上传进度  
				// uploadTask.onProgressUpdate((res) => {
				// 	// this.uploadPercent = res.progress; // 更新进度条  
				// 	console.log('上传进度', res.progress);
				// 	uni.setStorageSync("progress",res.progress)
				// 	console.log('已经上传的数据长度', res.totalBytesSent);
				// 	console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend);
				// });

			}
		})

	});
}




export function isAuthorize(scopeStr, permissionToast) {
	return new Promise((resolve, reject) => {
		// #ifdef MP-WEIXIN
		// 微信小程序验证是否开启授权
		uni.getSetting({
			success(res) {
				// 如果权限未开启
				if (!res.authSetting[scopeStr]) {
					uni.authorize({
						scope: scopeStr,
						// 允许授权
						success() {
							resolve(true)
						},
						// 拒绝授权
						fail() {
							uni.showModal({
								title: permissionToast.title,
								content: permissionToast.content,
								confirmText: "开启授权",
								cancelText: '取消',
								success: (res2) => {
									if (res2.confirm) {
										// 开启授权设置
										uni.openSetting({
											success: (res3) => {
												//设置后返回，不管开没开
												// 有回调触发回调
												if (permissionToast
													.callback) {
													permissionToast
														.callback();
												}
											}
										})
										reject(false)
									} else {
										// 用户拒绝授权或请求授权失败  
										uni.showToast({
											title: '您拒绝了'+permissionToast.title+'权限',
											icon: 'none'
										});
										reject(false)
										return false;
									}
								},
								fail: () => {
									reject(false)
								}
							})
						}
					})
				} else {
					// 已开启权限
					resolve(true)
				}
			}
		})
		// #endif
		// #ifdef APP-PLUS
		// APP权限验证
		permision.requestAndroidPermission(scopeStr).then(res => {
			// 1已授权 2 未授权 -1 永久拒绝授权
			// 2会自动调取弹窗 -1必须手动调取弹窗
			if (res == -1) {
				// 永久拒绝授权相册
				uni.showModal({
					title: permissionToast.title,
					content: permissionToast.content,
					confirmText: "开启权限",
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							permision.gotoAppPermissionSetting()
						} else {
							return false;
						}
					}
				})
			}
			resolve(res)
		}).catch(err => {
			reject(false)
		})
		// #endif
	})
}